﻿param([String]$Mode="StartUp")
##########
# ManageServices.ps1
# Manages services (including making sure latest config file is in place in the globally known location)
#

#region Function Definitions

########
# Stop the Director services if they are already running
function StopServices()
{
	
	# Stop the services if they are already running
	$SelfMapProc = Get-Process "SelfMap" -ErrorAction SilentlyContinue
	$PhysicalMapProc = Get-Process "PhysicalMap" -ErrorAction SilentlyContinue
	$WorldProc = Get-Process "World3D" -ErrorAction SilentlyContinue

	if ($SelfMapProc)
	{
		echo "Stopping SelfMap process"
		Stop-Process -name "SelfMap"
	}

	if ($PhysicalMapProc)
	{
		echo "Stoping PhysicalMap process"
		Stop-Process -name "PhysicalMap"
	}

	if ($WorldProc)
	{
		echo "Stoping World process"
		Stop-Process -name "World3D"
	}

	echo "All Director Processes Stopped"
}

########
# Copy the endpoint configuration file out to the global configuration path
function InstallEndpointConfFile()
{
	echo "Installing the Endpoint Configuration File"
	Remove-Item C:\InanimatedObjects\*.*
	# The web application needs the connection endpoints conf file in a known location so it can find the services
	Copy ..\..\Common\lib\ConnectionEndpoints.conf C:\InAnimatedObjects\	
}

#########
# Delete database files (*.db3), used during development as the schema evolves
function DeleteDataFiles()
{
	echo "Cleaning The World"
	del ..\..\World\Worlds\World3D\bin\Debug\*.db3

	echo "Cleaning Director executables"
	del ..\Binaries\Debug\*.db3
}

#########
# Start the services
function StartServices()
{
	echo "Starting The World"
	Start-Process -WorkingDirectory ..\..\World\Worlds\World3D\bin\Debug ..\..\World\Worlds\World3D\bin\Debug\World3D.exe

	echo "Starting SelfMap"
	Start-Process -WorkingDirectory ..\Binaries\Debug ..\Binaries\Debug\SelfMap.exe

	echo "Starting PhysicalMap"
	Start-Process -WorkingDirectory ..\Binaries\Debug ..\Binaries\Debug\PhysicalMap.exe
}

#endregion

########
# Main
StopServices

if ($Mode -eq "StartupClean")
{
	DeleteDataFiles
}

if ($Mode -like "Startup*")
{
	InstallEndpointConfFile
	StartServices
}